super KeywordLearn Runtime Polymorphism and Superclass Referencing with Visual Diagrams & Code Examples
When a subclass provides a specific implementation of a method that is already defined in its parent class.
@Override annotation for compiler safety.super KeywordA reference variable used inside a child class to access members of its immediate parent class.
super.methodName()super.variableNamesuper(...)When an overridden method is called using a superclass reference pointing to a child object, Java decides which method to run at runtime based on the actual object type.
class Animal {
void makeSound() {
System.out.println("Generic animal sound");
}
}
class Dog extends Animal {
@Override // Ensures correct signature
void makeSound() {
System.out.println("Bark! Bark!");
}
}
// Usage:
Animal myPet = new Dog();
myPet.makeSound(); // Output: Bark! Bark! (Runtime Polymorphism)
super KeywordThe super keyword bridges the gap between child logic and parent logic.
class Vehicle {
int maxSpeed = 120;
Vehicle(String type) {
System.out.println("Vehicle Constructor: " + type);
}
void start() {
System.out.println("Vehicle is starting...");
}
}
class Car extends Vehicle {
int maxSpeed = 200; // Hides parent maxSpeed
Car() {
super("Four-Wheeler"); // 1. Calls Parent Constructor (MUST be first line!)
}
@Override
void start() {
super.start(); // 2. Calls Parent Method
System.out.println("Car engine roaring!");
}
void showSpeeds() {
System.out.println("Car speed: " + maxSpeed); // 200
System.out.println("Vehicle speed: " + super.maxSpeed); // 3. Accesses Parent Variable (120)
}
}
Click through the tabs below to simulate how method overriding and super operate in real Java scenarios.
Animal a = new Cat();
a.sound(); // Calls Cat's sound() method at runtime
class Employee {
void work() { System.out.println("Working on general tasks..."); }
}
class Developer extends Employee {
@Override
void work() {
super.work(); // Execute base logic first
System.out.println("Writing Java Code!");
}
}
class Person {
Person(String name) { System.out.println("Person name: " + name); }
}
class Student extends Person {
Student(String name, int id) {
super(name); // Passes name to Person constructor
System.out.println("Student ID: " + id);
}
}
| Rule / Constraint | Can be Overridden? | Reason / Details |
|---|---|---|
| Instance Methods | YES | Standard target for dynamic runtime overriding. |
static Methods |
NO | Static methods belong to the class, not instances (Method Hiding, not overriding). |
final Methods |
NO | The final modifier prevents child classes from changing the method logic. |
private Methods |
NO | Private methods are not visible to child classes, so they cannot be overridden. |
| Constructors | NO | Constructors are not inherited; invoked via super() instead. |